package cn.leftshine.readme.helper;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;

import cn.leftshine.readme.R;
import cn.leftshine.readme.beans.ThemeItem;
import cn.leftshine.readme.listener.ThemeCacheRefreshListener;
import cn.leftshine.readme.listener.ThemeLoaderListener;
import solid.ren.skinlibrary.SkinConfig;
import solid.ren.skinlibrary.SkinLoaderListener;
import solid.ren.skinlibrary.loader.SkinManager;
import solid.ren.skinlibrary.utils.ResourcesCompat;
import solid.ren.skinlibrary.utils.SkinFileUtils;
import solid.ren.skinlibrary.utils.SkinPreferencesUtils;

/**
 * Created by Administrator on 2018/10/26.
 */

public class ThemeInfoHelper {
    private final static String TAG= "theme";
    public final static String DEFAULT_SKIN_FILE_NAME = "default.skin";

    private static String skinPackageName;
    static ArrayList<ThemeItem> items = new ArrayList<ThemeItem>();

    /*public static ArrayList<ThemeItem> getThemes(Context context, File skinDir){
        ArrayList<ThemeItem> items = new ArrayList<ThemeItem>();
        Log.i("theme", "getThemes: skinDir="+skinDir);
        if (!skinDir.exists()) {//判断路径是否存在
            return null;
        }

        File[] files = skinDir.listFiles();

        if(files==null){//判断权限
            return null;
        }

        for (File file : files) {//遍历目录
            if (file.isFile() && file.getName().endsWith(".skin")) {
                String name = file.getName();
                Log.i("theme", "getThemes: " + name);
                //从文件中获取主题名字和主题颜色的资源值存入items中
                Resources res = getApkFileRes(context,file.getPath());
                if (res != null) {
                    String themeName = res.getString(R.string.app_name);
                    int themeColor = res.getColor(R.color.colorPrimary);
                    items.add(new ThemeItem(themeName, themeColor));
                }
            }

        }
        return items;
    }*/

    /**
     * load skin form local
     * <p>
     * eg:theme.skin
     * </p>
     *  @param skinDir the Path of skin(in assets/skin)
     * @param callback load Callback
     */
    @SuppressLint("StaticFieldLeak")
    public static void getThemes(final Context context, final File skinDir, final ThemeLoaderListener callback) {


        new AsyncTask<File, Void, ArrayList<ThemeItem>>() {

            @Override
            protected void onPreExecute() {
                if (callback != null) {
                    callback.onStart();
                }
            }

            @Override
            protected ArrayList<ThemeItem> doInBackground(File... params) {
                try {
                    if (params.length == 1) {
                        /*String skinDirPath = params[0];
                        File skinDir = new File(skinDirPath);*/
                        ArrayList<ThemeItem> themeItems = new ArrayList<ThemeItem>();
                        File skinDir = params[0];
                        if (!skinDir.exists()) {//判断路径是否存在
                            return null;
                        }

                        File[] files = skinDir.listFiles();

                        if(files==null){//判断权限
                            return null;
                        }

                        for (File file : files) {//遍历目录
                            if (file.isFile() && file.getName().endsWith(".skin")) {
                                String themeFilename = file.getName();
                                Log.i("theme", "getThemes: " + themeFilename);
                                //从文件中获取主题名字和主题颜色的资源值存入items中
                                String skinPkgPath= file.getPath();
                                PackageManager mPm = context.getPackageManager();
                                PackageInfo mInfo = mPm.getPackageArchiveInfo(skinPkgPath, PackageManager.GET_ACTIVITIES);
                                skinPackageName = mInfo.packageName;
                                AssetManager assetManager = AssetManager.class.newInstance();
                                Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);
                                addAssetPath.invoke(assetManager, skinPkgPath);


                                Resources superRes = context.getResources();
                                Resources skinResource = ResourcesCompat.getResources(assetManager, superRes.getDisplayMetrics(), superRes.getConfiguration());
                                if (skinResource != null) {

                                    //String themeName = skinResource.getString(R.string.app_name);
                                    String themeName = skinResource.getString(skinResource.getIdentifier("app_name","string",skinPackageName));
                                    //int themeColor = skinResource.getColor(R.color.colorPrimary);
                                    int themeColor = skinResource.getColor(skinResource.getIdentifier("colorPrimary","color",skinPackageName));
                                    themeItems.add(new ThemeItem(themeFilename,themeName, themeColor));
                                }
                            }

                        }
                        return themeItems;
                    }
                    return null;
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }

            @Override
            protected void onPostExecute(ArrayList<ThemeItem> result) {
                items = result;

                if (items != null) {
                    if (callback != null) {
                        callback.onSuccess(items);
                    }
                } else {
                    if (callback != null) {
                        callback.onFailed("没有获取到主题资源");
                    }
                }
            }

        }.execute(skinDir);
    }

    public static void refreshThemeCache(final Context context, final ThemeCacheRefreshListener callback){
        new AsyncTask(){

            @Override
            protected void onPreExecute() {
                if (callback != null) {
                    callback.onStart();
                }
            }

            @Override
            protected void onPostExecute(Object o) {
                if ((Boolean)o){
                    if (callback != null) {
                        callback.onSuccess();
                    }
                }else{
                    if (callback != null) {
                        callback.onFailed("资源读取失败");
                    }
                }

            }

            @Override
            protected Object doInBackground(Object[] objects) {

                try {
                    cleanSkinFile(context);
                    setUpSkinFile(context);
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
                return true;
            }
        }.execute();


    }

    private static void cleanSkinFile(Context context){

            /*String[] skinFiles = context.getAssets().list(SkinConfig.SKIN_DIR_NAME);
            for (String fileName : skinFiles) {
                File file = new File(SkinFileUtils.getSkinDir(context), fileName);
                if (file.exists()) {
                    file.delete();
                }
            }*/
            File skinCacheDir =  new File(SkinFileUtils.getSkinDir(context));
            if(skinCacheDir.isDirectory()) {
                for(File file:skinCacheDir.listFiles()) {
                    file.delete();
                }
            }


    }
    private static void setUpSkinFile(Context context) throws IOException {
            String[] skinFiles = context.getAssets().list(SkinConfig.SKIN_DIR_NAME);
            for (String fileName : skinFiles) {
                File file = new File(SkinFileUtils.getSkinDir(context), fileName);
                if (!file.exists()) {
                    SkinFileUtils.copySkinAssetsToDir(context, fileName, SkinFileUtils.getSkinDir(context));
                }
            }
    }
}
